const Koa = require('koa');
// 在post请求路由中使用ctx.request.body即可返回post请求中的对象
const bodyParser = require('koa-bodyparser');
const path = require('path');
const router = require('./routes');
const serve = require('koa-static');
const cors = require('koa2-cors');
const koaBody = require('koa-body');
const app = new Koa();
const mongoose = require('mongoose')
const chalk = require('chalk')
const { dbUrl } = require('./config/config')
const { getIPAdress } = require('./utils/ip')
// 初始化数据库
mongoose.set('useFindAndModify', false)
mongoose.connect(dbUrl, { useCreateIndex: true, useUnifiedTopology: true, useNewUrlParser: true }, error => {
  if (error) {
    console.log(chalk.red('数据库连接失败'), error)
  } else {
    console.log(chalk.green('数据库连接成功。'))
  }
})
Date.prototype.Format = function (fmt = 'yyyy-MM-dd hh:mm:ss') {
  //author: meizz
  var o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + '').substr(4 - RegExp.$1.length),
    );
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
      );
  return fmt;
};

app.use(cors({
  credentials: true,//默认情况下，Cookie不包括在CORS请求之中。设为true，即表示服务器许可Cookie可以包含在请求中
}));

// app.use(async (ctx, next) => {
//   ctx.set('Access-Control-Allow-Credentials', true)
//   // ctx.set('Access-Control-Allow-Oriain', '*')
//   await next();
// });

app.use(koaBody({
  formidable: {
    //设置文件的默认保存目录，不设置则保存在系统临时目录下  
    uploadDir: path.resolve(__dirname, './static')
  },
  multipart: true // 支持文件上传
}));

// serve参数为静态文件目录
app.use(serve(path.resolve(__dirname, "./static")));
app.use(bodyParser());
router(app);


app.listen(4000, () => {
  // console.log(new Date().Format());
  // console.log('http://localhost:4000/test');
  console.log(getIPAdress());
});
